/**
 * Created by PhpStorm.
 * User: Devmc
 * Date: 2021/4/25
 * Time: 2:48
 */
import axios from "axios";
import store from '../store';
import router from '../router';
import {base64decode} from "crypto.js";
import Cookies from 'js-cookie';


/**
 * 是否登录
 *
 * @return {boolean}
 */
function isLogin() {
    return Object.keys(store.state.userData).length != 0;
}


/**
 * 登出
 */
function logout() {
    store.commit('setUserData', {});
    Cookies.remove('token');
    router.replace('/login');
}


/**
 * 登录获取用户信息到Vuex
 *
 * @param cookie
 * @param reLogin
 * @return {Promise<unknown>}
 */
function loginGetUserData(cookie = '', reLogin = false) {
    return new Promise((resolve, reject) => {
        if (!isLogin() || reLogin) {
            if (!cookie) cookie = Cookies.get('token');
            const split = cookie.split('+');
            const usm = base64decode(split[0]).toString('utf-8');
            const pwd = base64decode(split[1]).toString('utf-8');

            const url = store.state.api + `/user/list`;
            axios.post(url, {
                userName: usm,
                password: pwd
            }).then((response) => {
                if (response.data.code == 200) {
                    const data = response.data.data.records;
                    if (data.length) {
                        // 设置到Vuex
                        store.commit('setUserData', data[0]);
                        resolve();
                    }
                    else reject();
                }
                else reject();
            }).catch((error) => {
                reject();
                console.log(error);
            });
        }
        else resolve();
    });
}



/**
 * 根据ID获取用户信息
 *
 * @param id
 * @return {Promise<unknown>}
 */
function getUserDataById(id) {
    return new Promise((resolve, reject) => {
        axios.get(store.state.api + '/user/getById?userid=' + id)
            .then((response) => {
                if (response.data.code == 200) {
                    // 返回用户信息
                    if (response.data.data) {
                        resolve(response.data.data);
                    }
                    else reject();
                }
                else reject();
            })
            .catch((error) => {
                console.log(error);
                reject();
            });
    })
}


/**
 * 获取所有用户数据
 *
 * @return {Promise<unknown>}
 */
function getAllUserData() {
    // 获取
    return new Promise(resolve => {
        const url = store.state.api + '/user/list?pageNum=1&pageSize=500';
        axios.post(url, {}).then((response) => {
            if (response.data.code == 200) {
                const records = response.data.data.records;
                resolve(records);
            }
        }).catch((error) => {
            console.log(error);
        });
    });
}


/**
 * 把用户数据以id为健存为对象
 *
 * @return {Promise<unknown>}
 */
function getUserObjectData(update = false) {
    // 获取
    return new Promise(resolve => {
        if (update || store.state.userObjectData == null) {
            getAllUserData().then((records) => {
                // 组装数据
                if (records.length) {
                    let values = {};
                    records.forEach((item) => {
                        values[item.userId] = {};
                        Object.keys(item).forEach((key) => {
                            values[item.userId][key] = item[key];
                        })
                    });
                    store.commit('setUserObjectData', values);
                    resolve(values);
                }
            });
        }
        else resolve(store.state.userObjectData);
    });
}


/**
 * 根据Role获取用户信息
 *
 * @param role
 * @param body
 * @param page
 * @param size
 * @return {Promise<unknown>}
 */
function getUserDataByRole(role, body = {}, page = 1, size = 500) {
    const url = store.state.api + `/user/list?pageNum=${page}&pageSize=${size}`;

    // 把String转arr
    if (typeof role == 'string') role = [role];
    // 请求
    let req = role.map((item) => {
        return axios.post(url, Object.assign({role: item}, body));
    });

    return new Promise((resolve) => {
        Promise.all(req)
            .then(response => {
                let data = [];
                response.forEach((item) => {
                    item.data.data.records.forEach((item2) => {
                        data.push(item2);
                    });
                });
                resolve(data);
            })
            .catch(error => {
                console.log(error);
            });
    });
}


export default {
    isLogin,
    logout,
    loginGetUserData,
    getUserDataById,
    getAllUserData,
    getUserObjectData,
    getUserDataByRole
}
